<template>
  <view class="page">
    <uni-nav-bar title="商品" fixed></uni-nav-bar>
    <!-- 搜索 / 筛选 / 排序 -->
    <view class="toolbar">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999" />
        <input
          class="search-input"
          v-model="keyword"
          placeholder="搜索商品名称"
          confirm-type="search"
        />
        <view v-if="keyword" class="clear" @click="keyword = ''">
          <uni-icons type="closeempty" size="18" color="#c0c0c0" />
        </view>
      </view>
      <view class="toolbar-actions">
        <view
          class="action"
          @click="toggleSort('money')"
          :class="{ active: sortKey === 'money' && sortOrder !== null }"
        >
          <text class="action-text">价格</text>
          <view
            v-if="sortKey === 'money' && sortOrder !== null"
            class="sort-icon"
          >
            <uni-icons
              :type="sortOrder === 'asc' ? 'up' : 'down'"
              size="14"
              color="#1a6eff"
            />
          </view>
        </view>
        <view
          class="action"
          @click="toggleSort('stock')"
          :class="{ active: sortKey === 'stock' && sortOrder !== null }"
        >
          <text class="action-text">库存</text>
          <view
            v-if="sortKey === 'stock' && sortOrder !== null"
            class="sort-icon"
          >
            <uni-icons
              :type="sortOrder === 'asc' ? 'up' : 'down'"
              size="14"
              color="#1a6eff"
            />
          </view>
        </view>
        <view
          class="action"
          @click="toggleSort('sales')"
          :class="{ active: sortKey === 'sales' && sortOrder !== null }"
        >
          <text class="action-text">销量</text>
          <view
            v-if="sortKey === 'sales' && sortOrder !== null"
            class="sort-icon"
          >
            <uni-icons
              :type="sortOrder === 'asc' ? 'up' : 'down'"
              size="14"
              color="#1a6eff"
            />
          </view>
        </view>
      </view>
    </view>
    <uni-swipe-action>
      <view class="list" v-for="item in displayedList" :key="item.id">
        <uni-swipe-action-item class="list-item">
          <template v-slot:left>
            <!-- 左侧操作可根据需要添加 -->
          </template>
          <view class="content-box" @click="handleViewDetail(item)">
            <image
              class="stroeListItem-pic"
              :src="formatImageUrl(item.showPic)"
              mode="aspectFill"
            ></image>
            <view class="stroeListItem-right">
              <view class="top">{{ item.name }}</view>
              <view class="bottom">
                <view class="money">￥{{ item.money }}</view>
              </view>
              <view class="address"
                >状态：{{ item.status == 1 ? "已下架" : "已上架" }}</view
              >
            </view>
          </view>
          <template v-slot:right>
            <view class="slot-button danger" @click="handleDelete(item)"
              ><text class="slot-button-text">删除</text></view
            >
            <view
              class="slot-button primary"
              v-if="item.status == 1"
              @click="handleOnOff(item, 0)"
              ><text class="slot-button-text">上架</text></view
            >
            <view
              class="slot-button warning"
              v-if="item.status == 0"
              @click="handleOnOff(item, 1)"
              ><text class="slot-button-text">下架</text></view
            >
            <view class="slot-button success" @click="handleEdit(item)"
              ><text class="slot-button-text">编辑商品</text></view
            >
          </template>
        </uni-swipe-action-item>
      </view>
    </uni-swipe-action>

    <!-- 加载更多 -->
    <LoadMore v-if="list.length > 0" :status="loadStatus" />

    <!-- 右下角固定新增按钮 -->
    <view class="add-btn" @click="goAddGoods">
      <uni-icons type="plusempty" size="24" color="#fff" />
    </view>

    <!-- 筛选弹层 -->
    <uni-popup ref="filterPopup" type="bottom" background-color="#fff">
      <view class="filter-panel">
        <view class="filter-row">
          <text class="label">上架状态</text>
          <view class="chips">
            <view
              class="chip"
              :class="{ selected: tempStatusFilter === null }"
              @click="tempStatusFilter = null"
              >不限</view
            >
            <view
              class="chip"
              :class="{ selected: tempStatusFilter === 0 }"
              @click="tempStatusFilter = 0"
              >上架</view
            >
            <view
              class="chip"
              :class="{ selected: tempStatusFilter === 1 }"
              @click="tempStatusFilter = 1"
              >下架</view
            >
          </view>
        </view>
        <view class="filter-row">
          <text class="label">价格区间</text>
          <view class="range">
            <input
              class="range-input"
              type="number"
              v-model.number="tempPriceMin"
              placeholder="最低价"
            />
            <text class="dash">-</text>
            <input
              class="range-input"
              type="number"
              v-model.number="tempPriceMax"
              placeholder="最高价"
            />
          </view>
        </view>
        <view class="filter-actions">
          <button class="btn reset" @click="resetFilter">重置</button>
          <button class="btn confirm" @click="applyFilter">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { formatImageUrl } from "@/utils/filters";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import { useEditorStore } from "@/store/modules/editor";
import { getGoodsList, deleteGoods, goodsOnOff } from "@/api/goods";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";

// 使用 store
const userStore = useUserStore();
const storeStore = useStoreStore();
const editorStore = useEditorStore();

// 商品列表
const list = ref([]);
const page = ref(1);
const limit = ref(10); // 每页10条
const total = ref(0); // 总数
const loadStatus = ref("more"); // more, loading, nomore

// 搜索/筛选/排序状态
const keyword = ref("");
const sortKey = ref(null); // money | stock | sales | null (默认不排序)
const sortOrder = ref(null); // asc | desc | null (默认不排序)

// 实际生效的筛选条件
const statusFilter = ref(null); // null 不限, 0 上架, 1 下架
const priceMin = ref();
const priceMax = ref();

// 临时筛选条件（用于弹层中）
const tempStatusFilter = ref(null);
const tempPriceMin = ref();
const tempPriceMax = ref();

// 过滤后的可视列表（前端筛选，排序由后端处理）
const displayedList = computed(() => {
  let data = [...list.value];
  // 关键词
  if (keyword.value) {
    const k = keyword.value.trim().toLowerCase();
    data = data.filter((i) =>
      String(i.name || "")
        .toLowerCase()
        .includes(k)
    );
  }
  // 上下架
  if (statusFilter.value !== null) {
    data = data.filter((i) => Number(i.status) === Number(statusFilter.value));
  }
  // 价格区间
  if (priceMin.value != null && priceMin.value !== "") {
    data = data.filter((i) => Number(i.money || 0) >= Number(priceMin.value));
  }
  if (priceMax.value != null && priceMax.value !== "") {
    data = data.filter((i) => Number(i.money || 0) <= Number(priceMax.value));
  }
  return data;
});

// 打开筛选弹层
const filterPopup = ref(null);
const openFilter = () => {
  // 打开时，将当前生效的筛选条件复制到临时变量
  tempStatusFilter.value = statusFilter.value;
  tempPriceMin.value = priceMin.value;
  tempPriceMax.value = priceMax.value;
  filterPopup.value?.open();
};
const resetFilter = () => {
  // 重置临时变量
  tempStatusFilter.value = null;
  tempPriceMin.value = undefined;
  tempPriceMax.value = undefined;
};
const applyFilter = () => {
  // 应用临时变量到实际筛选条件
  statusFilter.value = tempStatusFilter.value;
  priceMin.value = tempPriceMin.value;
  priceMax.value = tempPriceMax.value;
  filterPopup.value?.close();
};
const toggleSort = (key) => {
  // 如果点击的是不同的排序字段，切换到该字段并设置为降序
  if (sortKey.value !== key) {
    sortKey.value = key;
    sortOrder.value = "desc";
  } else {
    // 如果点击的是当前排序字段，在三种状态之间切换：降序 -> 升序 -> 默认(null)
    if (sortOrder.value === "desc") {
      sortOrder.value = "asc";
    } else if (sortOrder.value === "asc") {
      sortOrder.value = null;
      sortKey.value = null;
    }
  }

  // 排序改变后，重置页码并重新获取数据
  page.value = 1;
  fetchGoodsList();
};

// 获取排序参数值
// 1.价格升序 2.价格降序 3.库存升序 4.库存降序 5.销量升序 6.销量降序
const getSortValue = () => {
  // 如果没有选择排序，返回 undefined (不传排序参数)
  if (sortKey.value === null || sortOrder.value === null) {
    return undefined;
  }

  const sortMap = {
    money: { asc: 1, desc: 2 }, // 价格
    stock: { asc: 3, desc: 4 }, // 库存
    sales: { asc: 5, desc: 6 }, // 销量
  };

  return sortMap[sortKey.value]?.[sortOrder.value];
};

// 获取商品列表
const fetchGoodsList = async (isLoadMore = false) => {
  // 如果是加载更多，检查是否还有数据
  if (isLoadMore && list.value.length >= total.value) {
    loadStatus.value = "nomore";
    return;
  }

  loadStatus.value = "loading";

  try {
    // 构建请求参数
    const params = {
      userId: userStore.userInfo?.userId,
      merchantId: storeStore.storeId,
      limit: limit.value,
      offset: page.value,
    };

    // 只有在有排序时才添加 sort 参数
    const sortValue = getSortValue();
    if (sortValue !== undefined) {
      params.sort = sortValue; // 1.价格升序 2.价格降序 3.库存升序 4.库存降序 5.销量升序 6.销量降序
    }

    const response = await getGoodsList(params);

    if (response?.data?.rows) {
      if (isLoadMore) {
        // 追加数据
        list.value = [...list.value, ...response.data.rows];
      } else {
        // 重置数据
        list.value = response.data.rows;
      }

      // 更新总数
      if (response.data.total !== undefined) {
        total.value = response.data.total;
      }

      // 判断是否还有更多数据
      if (list.value.length >= total.value) {
        loadStatus.value = "nomore";
      } else {
        loadStatus.value = "more";
      }
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    loadStatus.value = "more";
    uni.showToast({
      title: "获取商品列表失败",
      icon: "none",
    });
  }
};

// 删除商品
const handleDeleteGoods = async (id) => {
  try {
    const response = await deleteGoods({
      userId: userStore.userInfo?.userId,
      merchantId: storeStore.storeId,
      id,
    });

    if (response.code === 2000) {
      uni.showToast({
        title: "删除成功",
        icon: "none",
      });
      // 重置页码并重新获取列表
      page.value = 1;
      fetchGoodsList();
    }
  } catch (error) {
    console.error("删除商品失败:", error);
    uni.showToast({
      title: "删除失败",
      icon: "none",
    });
  }
};

// 商品上下架
const handleGoodsOnOff = async (id, status) => {
  try {
    const response = await goodsOnOff({
      userId: userStore.userInfo?.userId,
      merchantId: storeStore.storeId,
      id,
      status,
    });

    if (response.code === 2000) {
      uni.showToast({
        title: "操作成功",
        icon: "none",
      });
      // 重置页码并重新获取列表
      page.value = 1;
      fetchGoodsList();
    }
  } catch (error) {
    console.error("操作失败:", error);
    uni.showToast({
      title: "操作失败",
      icon: "none",
    });
  }
};

// 跳转到添加商品页面
const goAddGoods = () => {
  uni.navigateTo({
    url: "./addGoods",
  });
};

// 查看商品详情
const handleViewDetail = (item) => {
  uni.navigateTo({
    url: `./goodsDetail?type=view&goodsId=${item.id}`,
  });
};

// 编辑商品
const handleEdit = (item) => {
  uni.navigateTo({
    url: `./goodsDetail?type=edit&goodsId=${item.id}`,
  });
};

// 删除商品
const handleDelete = (item) => {
  uni.showModal({
    title: "提示",
    content: "确定删除此商品",
    success: (res) => {
      if (res.confirm) {
        handleDeleteGoods(item.id);
      }
    },
  });
};

// 商品上下架
const handleOnOff = (item, status) => {
  const msg = status === 0 ? "确定上架该商品" : "确定将该商品下架";
  uni.showModal({
    title: "提示",
    content: msg,
    success: (res) => {
      if (res.confirm) {
        handleGoodsOnOff(item.id, status);
      }
    },
  });
};

// 加载更多
const handleLoadMore = () => {
  // 检查是否正在加载或已经没有更多数据
  if (loadStatus.value === "loading" || loadStatus.value === "nomore") {
    return;
  }

  // 增加页码
  page.value++;
  // 加载更多数据
  fetchGoodsList(true);
};

// 刷新商品列表数据
const refreshData = () => {
  console.log("🔄 刷新商品列表数据");

  // 清空富文本编辑器内容
  editorStore.clearRichText();

  // 初始化用户信息
  userStore.hydrateFromStorage();
  storeStore.hydrateFromStorage();

  // 重置页码
  page.value = 1;
  // 获取商品列表
  fetchGoodsList();
};

// 页面显示时刷新数据（包括切换店铺后返回）
onShow(() => {
  // 清空富文本编辑器内容
  editorStore.clearRichText();
  // 刷新商品列表
  refreshData();
});

// 页面滚动到底部
onReachBottom(() => {
  handleLoadMore();
});
</script>

<style lang="scss">
.page {
  display: flex;
  flex-direction: column;
  padding-bottom: 150rpx;

  .toolbar {
    padding: 12rpx 16rpx;
    background: #fff;
    position: sticky;
    top: 88rpx; // 顶部 nav 高度适配
    z-index: 9;

    .search-box {
      display: flex;
      align-items: center;
      padding: 12rpx 16rpx;
      background: #f6f7f9;
      border-radius: 9999rpx;

      .search-input {
        flex: 1;
        padding: 0 12rpx;
        font-size: 26rpx;
      }
      .clear {
        padding-left: 6rpx;
      }
    }

    .toolbar-actions {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-top: 12rpx;

      .action {
        display: inline-flex;
        align-items: center;
        gap: 6rpx;
        padding: 10rpx 18rpx;
        background: #f6f7f9;
        border-radius: 9999rpx;
        color: #333;
        transition: all 0.2s ease;

        .action-text {
          font-size: 26rpx;
        }

        .sort-icon {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-left: 4rpx;
        }

        &.active {
          background: #e8f0ff;
          color: #1a6eff;
        }

        &:active {
          transform: scale(0.96);
        }
      }
    }
  }

  .list {
    .list-item {
      margin-top: 20rpx;

      .content-box {
        width: 100%;
        background-color: #ffffff;
        color: #000000;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        padding: 30rpx;

        .stroeListItem-pic {
          width: 200rpx;
          height: 200rpx;
          border-radius: 10rpx;
        }

        .stroeListItem-right {
          width: calc(100% - 240rpx);

          .top {
            font-size: 30rpx;
            font-weight: 600;
            display: -webkit-box;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
          }

          .bottom {
            display: flex;
            width: 100%;
            align-items: center;
            padding: 20rpx 0;

            .money {
              color: rgba(236, 65, 19, 1);
              font-size: 28rpx;
            }

            .btn {
              color: rgba(171, 168, 168, 0.88);
              font-size: 24rpx;
              text-decoration: line-through;
              margin-left: 2px;
            }
          }

          .address {
            font-size: 30rpx;
            font-weight: 600;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #ababab;
          }

          .look {
            background-color: #ffebd8;
            color: #e08e40;
            display: inline-block;
            margin-top: 40rpx;
            padding: 4rpx 10rpx;
          }
        }
      }

      .slot-button {
        /* #ifndef APP-NVUE */
        display: flex;
        height: 100%;
        /* #endif */
        flex: 1;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        padding: 0 20px;

        .slot-button-text {
          color: #ffffff;
          font-size: 14px;
        }
      }

      .warning {
        background-color: #e6a23c;
      }

      .primary {
        background-color: #409eff;
      }

      .success {
        background-color: #67c23a;
      }

      .danger {
        background-color: #f56c6c;
      }
    }
  }

  /* 右下角新增按钮 */
  .add-btn {
    position: fixed;
    right: 32rpx;
    bottom: 120rpx;
    z-index: 99;
    width: 112rpx;
    height: 112rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #e6a23c;
    border-radius: 50%;
    box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.92);
      box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
    }
  }

  /* 筛选弹层样式 */
  .filter-panel {
    padding: 32rpx 24rpx;
    padding-bottom: 120rpx;
    background: #fff;
    border-top-left-radius: 24rpx;
    border-top-right-radius: 24rpx;
    max-height: 80vh;
  }

  .filter-row {
    margin-bottom: 32rpx;

    .label {
      display: block;
      margin-bottom: 16rpx;
      color: #333;
      font-size: 28rpx;
      font-weight: 600;
    }

    .chips {
      display: flex;
      gap: 16rpx;
      flex-wrap: wrap;
    }

    .chip {
      padding: 14rpx 28rpx;
      background: #f6f7f9;
      border: 2rpx solid transparent;
      border-radius: 9999rpx;
      font-size: 26rpx;
      color: #666;
      transition: all 0.2s;

      &.selected {
        background: #e8f0ff;
        border-color: #1a6eff;
        color: #1a6eff;
        font-weight: 600;
      }

      &:active {
        transform: scale(0.96);
      }
    }

    .range {
      display: flex;
      align-items: center;
      gap: 12rpx;
    }

    .range-input {
      flex: 1;
      background: #f6f7f9;
      border: 2rpx solid #e8eaed;
      border-radius: 12rpx;
      padding: 16rpx 20rpx;
      font-size: 26rpx;
      color: #333;
      height: 68rpx;
      line-height: 68rpx;

      &:focus {
        border-color: #1a6eff;
        background: #fff;
      }
    }

    .dash {
      padding: 0 8rpx;
      color: #c0c0c0;
      font-size: 28rpx;
      font-weight: 600;
    }
  }

  .filter-actions {
    display: flex;
    gap: 16rpx;
    padding-top: 16rpx;
    margin-top: 24rpx;
    border-top: 1rpx solid #f0f0f0;

    .btn {
      flex: 1;
      border-radius: 12rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      border: none;

      &.reset {
        background: #f6f7f9;
        color: #666;

        &:active {
          background: #e8eaed;
        }
      }

      &.confirm {
        background: #fabc02;
        color: #fff;
        font-weight: 600;
      }
    }
  }
}

.content-text {
  font-size: 15px;
}

.example-body {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  justify-content: center;
  padding: 10px 0;
  background-color: #fff;
}

.button {
  border-color: #e5e5e5;
  border-style: solid;
  border-width: 1px;
  padding: 4px 8px;
  border-radius: 4px;
}

.button-text {
  font-size: 15px;
}
</style>
